package cn.tedu.ivos.geofence.service.impl;

import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.base.response.StatusCode;
import cn.tedu.ivos.geofence.mapper.GeofenceMapper;
import cn.tedu.ivos.geofence.pojo.dto.GeofenceParam;
import cn.tedu.ivos.geofence.pojo.dto.GeofenceQuery;
import cn.tedu.ivos.geofence.pojo.entity.Geofence;
import cn.tedu.ivos.geofence.pojo.vo.GeofenceVO;
import cn.tedu.ivos.geofence.service.GeofenceService;
import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivos.vehicle.pojo.vo.VehicleVO;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class GeofenceServiceImpl implements GeofenceService {
    @Autowired
    GeofenceMapper geofenceMapper;

    @Autowired
    VehicleMapper vehicleMapper;

    @Override
    public List<GeofenceVO> selectGeofence(GeofenceQuery query) {
        log.debug("查询围栏信息，参数：{}", query);
        List<GeofenceVO> list=geofenceMapper.selectGeofence(query);
        return list;
    }

    @Override
    public void saveGeofence(GeofenceParam geofenceParam) {
        Geofence geofence=new Geofence();
        BeanUtils.copyProperties(geofenceParam,geofence);
        //前端数据是k-v结构，后端数据库是json格式，所以需要转换
        HashMap<String,String> position=geofenceParam.getPosition();
        //准备JSON处理工具
        ObjectMapper objectMapper = new ObjectMapper();
        try {//这个方法如果传入null值或字段不匹配会抛异常，所以放置try-catch中来捕捉异常
         String positionStr =  objectMapper.writeValueAsString(position);
            if (geofenceParam.getId()!=null){
                geofenceMapper.update(geofence);
            }else {
                geofence.setStatus("1");
                geofence.setPosition(positionStr);
                geofence.setCreateTime(new Date());
                geofenceMapper.insert(geofence);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteGeofenceById(Long id) {
        VehicleQuery vehicleQuery=new VehicleQuery();
        vehicleQuery.setGeofenceId(id);
        List<VehicleVO> list=vehicleMapper.selectVehicle(vehicleQuery);
        if (list!=null&&list.size()>0){
            throw new ServiceException(StatusCode.OPERATION_FAILED);
        }else {
            geofenceMapper.deleteGeofenceById(id);
        }
    }

}
